/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2024-12-25
 * Time: 15:05
 */
public class test2 {
    /*
    LeetCode 143  重排链表
     */
    public void reorderList(ListNode head) {
        if(head==null || head.next==null || head.next.next==null){
            return ;
        }
        // 找链表的中间节点  （快慢双指针）
        ListNode slow = head;
        ListNode fast = head;
        while(fast !=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        // 逆序 （头插法）
        ListNode head2 = new ListNode(0);
        ListNode cur =  slow.next;
        slow.next = null;
        while(cur!=null){
            ListNode next = cur.next;
            cur.next = head2.next;
            head2.next = cur;
            cur = next;
        }
        // 合并链表
        ListNode cur1 = head;
        ListNode cur2 = head2.next;
        ListNode ret = new ListNode(0);
        ListNode prev = ret;
        while(cur1!=null){
            prev.next = cur1;
            prev = prev.next;
            cur1=cur1.next;
            if(cur2!=null){
                prev.next = cur2;
                prev=prev.next;
                cur2=cur2.next;
            }
        }
    }

    private class ListNode {
        int val;
        ListNode next;
        ListNode() {

        }
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val; this.next = next;
        }
    }
}
